<?php
namespace Guestbook\Controller;
use Think\Controller;
use Think\Model;

class UserController extends Controller {
    // 注册页
    public function register()
    {
        layout('Layout/layout');
        $this->display();
    }
    // 注册提交
    public function do_register()
    {
        
        $username = I('username');
        $password = I('password');
        $repassword = I('repassword');
        if(empty($username)){
            $this->error('用户名不能为空！');
        }
        if(empty($password)){
            $this->error('密码不能为空！');
        }
        if($repassword!=$password){
            $this->error('确认密码错误！');
        }

        //检测用户是否注册
        $model = new Model('user');
        $user = $model->where(array('username'=>$username))->find();
        if(!empty($user)){
            $this->error('用户名已存在！');
        }
        $data = array(
            'username' => $username,
            'password' => md5($password),
            'createdAt' => time()
        );
        if(!($model->add($data))){
            $this->error('注册失败！'.$model->getDbError());
        }else{
            $this->success('注册成功,请登录！',U('login'));
        }
    }
    // 用户登录页
    public function login()
    {
        layout('Layout/layout');
        $this->display();
    }
    // 登录处理
    public function do_login()
    {
        $username = I('username');
        $password = I('password');
        $model = new Model('user');
        $user = $model->where(array('username'=>$username))->find();
        if(empty($user)||$user['password']!=md5($password)){
            $this->error('账号或密码错误！');
        }
        // 写入session
       $userID = session('user.userId',$user['userid']);
       $userNAMES = session('user.username',$user['username']);
    //    dump($user);
        // 跳转到首页
        $this->redirect('Index/index');
    }
    // 退出登录
    public function logout()
    {
        if(!session('user.username')){
            $this->error('请登录');
        }
        session_destroy();
        $this->success('退出登录',U('Index/index'));
    }
}